package org.sample.controller;

import org.sample.model.APIResult;
import org.sample.commons.CaptchaImg;
import org.sample.commons.lang.RandomUtils;
import org.sample.config.SessionKey;
import org.sample.entity.User;
import org.sample.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@Controller
public class HomeController {

    @Autowired
    private UserService userService;

    @RequestMapping(path = "user/login", method = RequestMethod.POST)
    @ResponseBody
    public APIResult login(String username, String password, String captcha, HttpSession session) {
//        if (!captcha.equalsIgnoreCase((String) session.getAttribute(SessionKey.Captcha.value)))
//            return new APIResult(ResultCodes.InvalidCaptcha);
        User user = userService.login(username, password);

        Object url = session.getAttribute(SessionKey.RequestUrl);
        if (url == null)
            url = "/manage/menu";
        session.removeAttribute(SessionKey.RequestUrl);
        session.removeAttribute(SessionKey.Captcha);
        session.setAttribute(SessionKey.User, user);
        return new APIResult(url);
    }

    @RequestMapping(path = "manage/menu", method = RequestMethod.GET)
    public String menu() {
        return "home/menu";
    }

    @RequestMapping(path = "user/logout", method = RequestMethod.GET)
    public String logout(HttpSession session) {
        session.removeAttribute(SessionKey.User);
        return "redirect:/login.html";
    }

    @RequestMapping(path = "user/captcha", method = RequestMethod.GET)
    public void captcha(HttpServletResponse response, HttpSession session) throws IOException {
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setContentType("image/jpeg");

        String captcha = RandomUtils.nextString(RandomUtils.ALPHABETIC, 4);
        session.setAttribute(SessionKey.Captcha, captcha);
        CaptchaImg.writeImage(captcha, response.getOutputStream());
    }
}